#! /bin/bash

# 支持管道和参数输入token
if [ $# -eq 6 ];then
  read -s sftp_pword
  sftp_local_file=$5
  sftp_remote_file=$6
elif [ $# -eq 7 ];then
  sftp_pword=$5
  sftp_local_file=$6
  sftp_remote_file=$7
else
  echo "$# para, input para num invalid, exit 1."
  exit 1
fi

sftp_method=$1
sftp_ip=$2
sftp_port=$3
sftp_user=$4


sftp_get()
{
  /usr/bin/expect <<-EOF
  set timeout -1
  spawn sftp -P ${sftp_port} ${sftp_user}@${sftp_ip}
  expect {
  "*not*" {exit 1}
  "*denied*" {exit 1}
  "*yes/no*" { send "yes\r"; exp_continue }
  "*assword:" { send "${sftp_pword}\r" }
  }

  expect {
  "*not*" {exit 1}
  "*denied*" {exit 1}
  "sftp>"
  }
  send "get ${sftp_remote_file} ${sftp_local_file} \r"
  expect {
  "*not*" {exit 1}
  "*denied*" {exit 1}
  "sftp>"
  }
  send "bye\r"
  expect eof
EOF
  exit $?
}

sftp_put()
{
  /usr/bin/expect <<-EOF
  set timeout -1
  spawn sftp -P ${sftp_port} ${sftp_user}@${sftp_ip}
  expect {
  "*not*" {exit 1}
  "*denied*" {exit 1}
  "*yes/no*" { send "yes\r"; exp_continue }
  "*assword:" { send "${sftp_pword}\r" }
  }

  expect {
  "*not*" {exit 1}
  "*denied*" {exit 1}
  "sftp>"
  }
  send "put ${sftp_local_file} ${sftp_remote_file} \r"
  expect {
  "*not*" {exit 1}
  "*denied*" {exit 1}
  "sftp>"
  }
  send "bye\r"
  expect eof
EOF
  exit $?
}


if [[ ${sftp_method} == "get" ]];then
  sftp_get
fi

if [[ ${sftp_method} == "put" ]];then
  sftp_put
fi

sftp_pword=" "

